
package me.zhengjie.service.impl;

import me.zhengjie.base.AjaxResult;
import me.zhengjie.domain.AppDoc;
import me.zhengjie.domain.AppDocCate;
import me.zhengjie.domain.AppDocFav;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.service.AppDocCateService;
import me.zhengjie.service.AppDocFavService;
import me.zhengjie.service.dto.*;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.repository.AppDocRepository;
import me.zhengjie.service.AppDocService;
import me.zhengjie.service.mapstruct.AppDocMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author IQW
* @date 2022-07-18
**/
@Service
@RequiredArgsConstructor
public class AppDocServiceImpl implements AppDocService {

    private final AppDocRepository appDocRepository;
    private final AppDocMapper appDocMapper;
    private final AppDocCateService appDocCateService;
    private final AppDocFavService appDocFavService;
    private final UserService userService;
    private final RoleService roleService;

    @Override
    public Map<String,Object> queryAllApi(AppDocQueryCriteria criteria, Pageable pageable){

        Integer fid = criteria.getType();
        if(null != criteria.getCateId() && criteria.getCateId() == 0){
            criteria.setCateId(criteria.getType());
            criteria.setType(null);
        }
        if(null != criteria.getCateId() && criteria.getCateId() != 0){
            //获取子集
            List<AppDocCate> list = appDocCateService.findByFid(criteria.getCateId());
            List<Integer> sons = appDocCateService.getChildrenIds(list);
            //同时把父级也加入
            sons.add(criteria.getCateId());
            criteria.getCateIds().addAll(sons);
            criteria.setStatus(1);
            //默认条件置空
            criteria.setCateId(null);
        }

        //查看当前责任区
        Long userId = SecurityUtils.getCurrentUserId();
        UserDto user = userService.findById(userId);
        criteria.setAreaId(user.getAreaId());

        Page<AppDoc> page = appDocRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);

        Page<AppDocDto> page2 = page.map(appDocMapper::toDto);
        //查询用户信息
        page2.getContent().forEach(appDocDto -> {
            //查询用户是否收藏
            Boolean fav = appDocFavService.findIsFav(SecurityUtils.getCurrentUserId().intValue(),appDocDto.getDocId());
            if(fav){
                appDocDto.setFav(1);
            }else{
                appDocDto.setFav(0);
            }
//            appDocDto.setAddTime(DateUtils.TimestampToStrDay(appDocDto.getCreateTime()));
//            if(null != criteria.getIsFav() && criteria.getIsFav() == 1){
//                //仅查看收藏的
//                if(!fav){
//                    appDocDto = null;
//                }
//            }

        });

        //查询文档分类
        AppDocCateQueryCriteria criteriaCate = new AppDocCateQueryCriteria();
        criteriaCate.setFid(fid);
        criteriaCate.setStatus(1);
        List<AppDocCateDto> listCate = appDocCateService.queryAll(criteriaCate);

        Map<String, Object> ret = new HashMap();
        ret.put("list",page2.getContent());
        ret.put("cateList",listCate);

        return AjaxResult.success(ret);
    }

    @Override
    public Map<String,Object> queryAll(AppDocQueryCriteria criteria, Pageable pageable){

        if(null != criteria.getCateId() && criteria.getCateId() != 0){
            //获取子集
            List<AppDocCate> list = appDocCateService.findByFid(criteria.getCateId());
            List<Integer> sons = appDocCateService.getChildrenIds(list);
            //同时把父级也加入
            sons.add(criteria.getCateId());
            criteria.getCateIds().addAll(sons);
            //默认条件置空
            criteria.setCateId(null);
        }
        if(null != criteria.getType2() && criteria.getType2() == 0){
            criteria.setType2(null);
        }

        //获取最小权限
        Integer currentLevel =  Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
        System.out.println("min level:"+currentLevel);
        if(currentLevel<=2){
            //管理员查看所有
        }else{
            //查看当前责任区
            Long userId = SecurityUtils.getCurrentUserId();
            UserDto user = userService.findById(userId);
            criteria.setAreaId(user.getAreaId());
        }

        Page<AppDoc> page = appDocRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(appDocMapper::toDto));
    }

    @Override
    public List<AppDocDto> queryAll(AppDocQueryCriteria criteria){
        return appDocMapper.toDto(appDocRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public AppDocDto findById(Integer docId) {
        AppDoc appDoc = appDocRepository.findById(docId).orElseGet(AppDoc::new);
        ValidationUtil.isNull(appDoc.getDocId(),"AppDoc","docId",docId);
        return appDocMapper.toDto(appDoc);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppDocDto create(AppDoc resources) {
        //检测图片类型
        if(!StringUtils.isEmpty(resources.getUrl())) {
            String ext = ImageUtils.getFileExtension(resources.getUrl());
            if (ImageUtils.isImage(ext)) {
                resources.setType2(1);
                resources.setIcon(resources.getUrl());
            } else {
                resources.setType2(2);
                resources.setIcon("http://ydweb.tentrue.com:8086/show/default_doc.png");
            }
        }

        resources.setClick(1);
        resources.setOrdid(255);
        resources.setStatus(1);

        //查看当前责任区
        Long userId = SecurityUtils.getCurrentUserId();
        UserDto user = userService.findById(userId);
        resources.setAreaId(user.getAreaId());

        resources.setCreateTime(DateUtils.getNowTimestamp());
        return appDocMapper.toDto(appDocRepository.save(resources));
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult actFav(AppDoc resources) {

        if(null == resources.getDocId() || resources.getDocId() == 0 ){
            return AjaxResult.error("参数错误");
        }
        if(resources.getType() == 1) {
            AppDocFav docFav = new AppDocFav();
            docFav.setDocId(resources.getDocId());
            docFav.setUserId(SecurityUtils.getCurrentUserId().intValue());
            docFav.setCreateTime(DateUtils.getNowTimestamp());
            appDocFavService.create(docFav);
            return AjaxResult.success("收藏成功");

        }else {
            //取消收藏
            AppDocFav docFav = new AppDocFav();
            docFav.setDocId(resources.getDocId());
            docFav.setUserId(SecurityUtils.getCurrentUserId().intValue());

            appDocFavService.deleteOne(SecurityUtils.getCurrentUserId().intValue(),resources.getDocId());
            return AjaxResult.success("取消成功");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AppDoc resources) {
        AppDoc appDoc = appDocRepository.findById(resources.getDocId()).orElseGet(AppDoc::new);
        ValidationUtil.isNull( appDoc.getDocId(),"AppDoc","id",resources.getDocId());
        appDoc.copy(resources);
        appDocRepository.save(appDoc);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer docId : ids) {
            appDocRepository.deleteById(docId);
        }
    }

    @Override
    public void download(List<AppDocDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AppDocDto appDoc : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("责任区ID", appDoc.getAreaId());
            map.put("名称", appDoc.getTitle());
            map.put("1政策文件，2知识文档", appDoc.getType());
            map.put("分类ID", appDoc.getCateId());
            map.put("1图片，2文档，3其它", appDoc.getType2());
            map.put("图标", appDoc.getIcon());
            map.put("下载路径", appDoc.getUrl());
            map.put("浏览量", appDoc.getClick());
            map.put("排序，越小越靠前", appDoc.getOrdid());
            map.put("状态", appDoc.getStatus());
            map.put(" createTime",  appDoc.getCreateTime());
            map.put(" updateTime",  appDoc.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}